package com.lottery.ruok.lottrey.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.applozic.mobicomkit.ApplozicClient;
import com.applozic.mobicomkit.api.account.user.UserLogoutTask;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.dialog.FingerPrintDialog;
import com.lottery.ruok.lottrey.eventbusObject.FingerSet;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.LogOutRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.OperationSuccessResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import property.SharePreferenceProperties;
import ui.LineRecordView;
import utils.Utils;
/*
 * 设置
 * */

public class SetActivity extends BaseActivity {
    public final static String ANALYTIC_VERSION = "1.0";

    @BindView(R.id.check_update)
    LineRecordView checkUpdate;
    @BindView(R.id.about_us)
    LineRecordView aboutUs;
    @BindView(R.id.logout)
    TextView logout;
    @BindView(R.id.login_password)
    LineRecordView loginPassword;
    @BindView(R.id.cash_password)
    LineRecordView cashPassword;
    @BindView(R.id.fingerprint_layout)
    RelativeLayout fingerprintLayout;
    @BindView(R.id.fingerprint)
    SwitchCompat fingerprint;
    @BindView(R.id.close_push_button)
    SwitchCompat close_push_button;
    @BindView(R.id.sound)
    SwitchCompat sound;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setFinger(FingerSet finger) {
        fingerprint.setOnCheckedChangeListener(null);
        if (finger.getType() == 1) {
            fingerprint.setChecked(false);
        } else if (finger.getType() == 2) {
            fingerprint.setChecked(true);
        }
        setSlideListener();
    }

    private void setSlideListener() {
        fingerprint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    Intent intent = new Intent(SetActivity.this, FingerPrintDialog.class);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                    //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_fingerprint_toggle_open");
                } else {
                    Intent intent = new Intent(SetActivity.this, FingerPrintDialog.class);
                    intent.putExtra("type", 2);
                    startActivity(intent);
                    //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_fingerprint_toggle_close");
                }
            }
        });
    }

    private void init() {
        checkUpdate.setRightTitle("当前版本" + Utils.getVersionName());

        if (UserInfo.getToken().equals("")) {
            logout.setVisibility(View.GONE);
        } else {
            logout.setVisibility(View.VISIBLE);
        }

        if (ApplozicClient.getInstance(getApplicationContext()).isNotificationDisabled()) {
            close_push_button.setChecked(true);
        } else {
            close_push_button.setChecked(false);
        }
        close_push_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_close_push");
                    ApplozicClient.getInstance(getApplicationContext()).disableNotification();

                } else {
                    ApplozicClient.getInstance(getApplicationContext()).enableNotification();

                }
            }
        });

        if (isFingerprintAuthAvailable()) {
            if (UserInfo.getFingerLock()) {
                fingerprint.setChecked(true);
            } else {
                fingerprint.setChecked(false);
            }

            fingerprintLayout.setVisibility(View.VISIBLE);

            setSlideListener();
        } else {
            fingerprintLayout.setVisibility(View.GONE);
        }


        String conversationCureChange = SharePreferenceProperties.get("conversationCureChange", "").toString();
        if (conversationCureChange != null && !"".equals(conversationCureChange)) {
            sound.setChecked(false);
        } else {
            sound.setChecked(true);
        }
        sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharePreferenceProperties.set("conversationCureChange", "");
                    setRongYunCure(Conversation.ConversationNotificationStatus.NOTIFY);
                } else {
                    SharePreferenceProperties.set("conversationCureChange", "close");
                    setRongYunCure(Conversation.ConversationNotificationStatus.DO_NOT_DISTURB);
                }
            }
        });


    }

    private void setRongYunCure(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
        RongIM.getInstance().setConversationNotificationStatus(Conversation.ConversationType.PRIVATE, null, conversationNotificationStatus, null);

    }


    /**
     * 判断是否具有指纹识别功能和是否已经设置指纹
     */
    @SuppressLint("NewApi")
    public boolean isFingerprintAuthAvailable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断当前手机版本
            KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);//获得密码管理器
            if (!mKeyguardManager.isKeyguardSecure()) {//判断是否具有锁屏密码
                return false;
            }
            if (checkSelfPermission(Manifest.permission.USE_FINGERPRINT) == PackageManager.PERMISSION_GRANTED) {//判断APP是否具有指纹识别权限
                FingerprintManager manager = (FingerprintManager) getSystemService(Activity.FINGERPRINT_SERVICE); //获得指纹识别管理器对象
                //判断是否具有指纹识别的硬件设施和是否已经录好指纹
                if (manager != null) {
                    return manager.isHardwareDetected() && manager.hasEnrolledFingerprints();
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private void logOutAction() {
        Utils.createDialog(this, "确定要退出吗？", "是的", "点错了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                RetrofitBase.getRetrofit().create(LogOutRequest.class)
                        .getResult(UserInfo.getToken())
                        .compose(RxHelper.<OperationSuccessResponse>handleResult())
                        .subscribe(new RxSubscribe<OperationSuccessResponse>(SetActivity.this) {
                            @Override
                            protected void _onNext(OperationSuccessResponse operationSuccessResponse) {
                                UserLogoutTask.TaskListener userLogoutTaskListener = new UserLogoutTask.TaskListener() {
                                    @Override
                                    public void onSuccess(Context context) {

                                    }

                                    @Override
                                    public void onFailure(Exception exception) {

                                    }
                                };
                                UserLogoutTask userLogoutTask = new UserLogoutTask(userLogoutTaskListener, SetActivity.this);
                                userLogoutTask.execute((Void) null);

                                logOut();
                                finish();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);

                                UserLogoutTask.TaskListener userLogoutTaskListener = new UserLogoutTask.TaskListener() {
                                    @Override
                                    public void onSuccess(Context context) {

                                    }

                                    @Override
                                    public void onFailure(Exception exception) {

                                    }
                                };
                                UserLogoutTask userLogoutTask = new UserLogoutTask(userLogoutTaskListener, SetActivity.this);
                                userLogoutTask.execute((Void) null);

                                logOut();
                                finish();
                            }

                            @Override
                            protected boolean showDialog() {
                                return true;
                            }
                        });
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
    }

    @OnClick({R.id.check_update, R.id.about_us, R.id.logout, R.id.login_password, R.id.cash_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check_update:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_version_detect");
                checkUpdate(true, true);
                break;
            case R.id.about_us:
                startActivity(new Intent(SetActivity.this, AboutActivity.class));
                break;
            case R.id.logout:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_quit_login");
                logOutAction();
                break;
            case R.id.login_password:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_modifypwd_jump");
                if (UserInfo.getToken().equals("")) {
                    gotoLoginActivity();
                } else {
                    startActivity(new Intent(SetActivity.this, ResetPasswordActivity.class));
                }
                break;
            case R.id.cash_password:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_modifymoneypwd_jump");
                if (UserInfo.getToken().equals("")) {
                    gotoLoginActivity();
                } else {
                    updateAccount(new AfterUpdateAccount() {
                        @Override
                        public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                            UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                            UserInfo.setUsername(getProfileResponse.getUser().getUsername());
                            UserInfo.setNickname(getProfileResponse.getUser().getNickname());
                            UserInfo.setMobilePhone(getProfileResponse.getUser().getMobile_phone());
                            if (getProfileResponse.getUser().getWithdraw_password() == 1) {
                                //进入修改资金密码界面
                                startActivity(new Intent(SetActivity.this, ChangeWithdrawPasswordActivity.class));
                            } else {
                                Utils.createDialog(SetActivity.this, "您没有设置资金密码，请第一时间设置资金密码", "去设置", "知道了",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                Intent intent = new Intent(SetActivity.this, MoneyPasswordActivity.class);
                                                intent.putExtra("source", 1);
                                                startActivity(intent);
                                            }
                                        },
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        });
                            }
                        }
                    }, true);
                }
                break;
        }
    }

}